package priv.stones.controller.administrate.shiro;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import priv.stones.common.exception.StonesException;
import priv.stones.entity.SysAdmin;

/**
 * @Author: Stones
 * @Description:
 * @Date: 2017/10/11 9:44
 */
public class ShiroUtils {
    //超级管理员
    public final static String SuperAdmin = "stones";
    //加密算法
    public final static String hashAlgorithmName = "SHA-256";
    //循环次数
    public final static int hashIterations = 16;

    /**
     * sha256加密
     *
     * @param password
     * @param salt
     * @return
     */
    public static String sha256(String password, String salt) {
        return new SimpleHash(hashAlgorithmName, password, salt, hashIterations).toString();
    }

    public static Session getSession() {
        return SecurityUtils.getSubject().getSession();
    }

    public static Subject getSubject() {
        return SecurityUtils.getSubject();
    }

    /**
     * 获取当前登录管理员
     *
     * @return
     */
    public static SysAdmin getAdmin() {
        return (SysAdmin) getSubject().getPrincipal();
    }

    /**
     * 设置属性到Shiro
     *
     * @param key
     * @param value
     */
    public static void setSessionAttribute(Object key, Object value) {
        getSession().setAttribute(key, value);
    }

    public static Object getSessionAttribute(Object key) {
        return getSession().getAttribute(key);
    }

    /**
     * 获取当前验证码
     *
     * @param key
     * @return
     */
    public static String getKaptcha(String key) {
        Object kaptcha = getSessionAttribute(key);
        if (kaptcha == null) {
            throw new StonesException("验证码已失效");
        }
        getSession().removeAttribute(key);
        return kaptcha.toString();
    }

    /**
     * 退出
     */
    public static void Logout() {
        SecurityUtils.getSubject().logout();
    }

}
